package com.beau.service.impl;

import com.beau.dao.TokenDao;
import com.beau.pojo.Token;
import com.beau.service.UserService;
import com.beau.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TokenDao tokenDao;


    @Override
    public boolean isRegistered(String email) {
        Token token = tokenDao.findByEmail(email);
        return token != null;
    }

    /**
     * 根据 token 查询 email
     * @param token
     * @return
     */
    @Override
    public String findEmail(String token) {
        Token tokenEntry = tokenDao.findByToken(token);
        if (tokenEntry != null) {
            return tokenEntry.getEmail();
        }
        return null;
    }

    @Override
    public void saveToken(String email, String token) {
        Token tokenEntry = new Token();
        tokenEntry.setEmail(email);
        tokenEntry.setToken(token);
        tokenDao.save(tokenEntry);
    }

    @Override
    public Boolean validate(String email, String passwd) {
        Token token = tokenDao.findByEmail(email);
        // token 不存在，说明没有注册
        if (token == null) {
            return false;
        }
        String newToken = TokenUtil.genToken(email+ ":" + passwd);
        // 验证 token 是否正确
        return newToken.equals(token.getToken());
    }

}
